using MediatR;
using RBAC.ErrorCode;
using RBAC.Write.Api.Application.Command.ERP.PurchasingManagement.RawMaterialSuppliers;
using Dapper;
using Microsoft.Extensions.Logging;
using RBAC.Interstructrue.Base;
using System.Data;

namespace RBAC.Write.Api.Application.Handler.ERP.PurchasingManagement.RawMaterialSuppliers
{
    /// <summary>
    /// 添加供应商命令处理
    /// </summary>
    public class AddRawMaterialSupplierCommandHandlters : IRequestHandler<AddRawMaterialSupplierCommand, APIResult<int>>
    {

        private readonly IDbConnectionFactory _connectionFactory;
        private readonly ILogger<AddRawMaterialSupplierCommandHandlters> _logger;

        public AddRawMaterialSupplierCommandHandlters(IDbConnectionFactory connectionFactory, ILogger<AddRawMaterialSupplierCommandHandlters> logger)
        {
            _connectionFactory = connectionFactory;
            _logger = logger;
        }

        public async Task<APIResult<int>> Handle(AddRawMaterialSupplierCommand request, CancellationToken cancellationToken)
        {
            var result = new APIResult<int>();

            // 基础校验
            if (string.IsNullOrWhiteSpace(request.Supplier_Name))
            {
                result.Code = APIEnums.Fail;
                result.Msg = "供应商名称不能为空";
                result.Data = 0;
                return result;
            }

            try
            {
                using var connection = _connectionFactory.CreateConnectionWithRetry();
                using var transaction = connection.BeginTransaction();

                try
                {
                    // 1. 插入主表 Supplier，返回自增ID
                    var insertSupplierSql = @"INSERT INTO Supplier
                        (Supplier_Name, Supplier_Alias, Short_Name, Province_City, Supply_Category, Supplier_Level, Supply_Products,
                         Company_Address, Postal_Code, Phone, Remarks, Status, CreateTime, CreateUser, IsDeleted)
                        VALUES
                        (@Supplier_Name, @Supplier_Alias, @Short_Name, @Province_City, @Supply_Category, @Supplier_Level, @Supply_Products,
                         @Company_Address, @Postal_Code, @Phone, @Remarks, @Status, NOW(), 'system', 0);
                        SELECT LAST_INSERT_ID();";

                    var supplierId = await connection.QueryFirstOrDefaultAsync<long>(
                        new CommandDefinition(insertSupplierSql, new
                        {
                            request.Supplier_Name,
                            request.Supplier_Alias,
                            request.Short_Name,
                            request.Province_City,
                            request.Supply_Category,
                            request.Supplier_Level,
                            request.Supply_Products,
                            request.Company_Address,
                            request.Postal_Code,
                            request.Phone,
                            request.Remarks,
                            request.Status
                        }, transaction: transaction, cancellationToken: cancellationToken));

                    // 2. 插入业务联系人 SupplierBusiness（可选）
                    if (!string.IsNullOrWhiteSpace(request.BusinessContact_Name) || !string.IsNullOrWhiteSpace(request.BusinessMobile_Phone))
                    {
                        var insertBusinessSql = @"INSERT INTO SupplierBusiness (Supplier_Id, Contact_Name, Mobile_Phone, IsDel)
                                                  VALUES (@Supplier_Id, @Contact_Name, @Mobile_Phone, 0);";

                        await connection.ExecuteAsync(
                            new CommandDefinition(insertBusinessSql, new
                            {
                                Supplier_Id = supplierId,
                                Contact_Name = request.BusinessContact_Name,
                                Mobile_Phone = request.BusinessMobile_Phone
                            }, transaction: transaction, cancellationToken: cancellationToken));
                    }

                    // 3. 插入财务联系人 SupplierFinance（可选）
                    if (!string.IsNullOrWhiteSpace(request.FinanceContact_Name) || !string.IsNullOrWhiteSpace(request.FinanceMobile_Phone))
                    {
                        var insertFinanceSql = @"INSERT INTO SupplierFinance (Supplier_Id, Contact_Name, Mobile_Phone, IsDel)
                                                 VALUES (@Supplier_Id, @Contact_Name, @Mobile_Phone, 0);";

                        await connection.ExecuteAsync(
                            new CommandDefinition(insertFinanceSql, new
                            {
                                Supplier_Id = supplierId,
                                Contact_Name = request.FinanceContact_Name,
                                Mobile_Phone = request.FinanceMobile_Phone
                            }, transaction: transaction, cancellationToken: cancellationToken));
                    }

                    // 4. 插入开票信息 SupplierInvoice（可选）
                    if (!string.IsNullOrWhiteSpace(request.Bank_Name) ||
                        !string.IsNullOrWhiteSpace(request.Bank_Address) ||
                        !string.IsNullOrWhiteSpace(request.Account_Number) ||
                        !string.IsNullOrWhiteSpace(request.Tax_Number))
                    {
                        var insertInvoiceSql = @"INSERT INTO SupplierInvoice (Supplier_Id, Bank_Name, Bank_Address, Account_Number, Tax_Number, IsDel)
                                                 VALUES (@Supplier_Id, @Bank_Name, @Bank_Address, @Account_Number, @Tax_Number, 0);";

                        await connection.ExecuteAsync(
                            new CommandDefinition(insertInvoiceSql, new
                            {
                                Supplier_Id = supplierId,
                                request.Bank_Name,
                                request.Bank_Address,
                                request.Account_Number,
                                request.Tax_Number
                            }, transaction: transaction, cancellationToken: cancellationToken));
                    }

                    // 提交事务
                    transaction.Commit();

                    // 返回新建供应商ID（注意数据库为bigint，这里转换为int以满足APIResult<int>）
                    result.Code = APIEnums.Success;
                    result.Msg = "添加供应商成功";
                    result.Data = (int)supplierId;
                    return result;
                }
                catch (Exception ex)
                {
                    try { transaction.Rollback(); } catch { }
                    _logger.LogError(ex, "添加供应商失败");
                    result.Code = APIEnums.Error;
                    result.Msg = $"添加供应商失败: {ex.Message}";
                    result.Data = 0;
                    return result;
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "数据库连接或事务创建失败");
                result.Code = APIEnums.Error;
                result.Msg = $"数据库异常: {ex.Message}";
                result.Data = 0;
                return result;
            }
        }
    }
}
